<script setup lang="ts">
import { onMounted, useTemplateRef } from 'vue';

const usingRef = useTemplateRef<HTMLCanvasElement>('using');
onMounted(() => {
    const canvas = usingRef.value!.querySelector('canvas') as HTMLCanvasElement;

    /* 让 canvas 内部像素尺寸与 css 尺寸一致，避免拉伸 */
    const { width, height } = canvas.getBoundingClientRect();

    const canvas2 = document.createElement('canvas');
    canvas2.width = width;
    canvas2.height = height;
    const ctx2 = canvas2.getContext('2d')!;

    ctx2.fillStyle = '#c64b4b';

    // 1. 保存画布状态
    ctx2.fillRect(0, 0, width, height);

    const ctx = canvas.getContext('2d')!;
    canvas.width = width;
    canvas.height = height;

    ctx.drawImage(canvas2, 0 - width / 2, 0, width, height);
});
</script>

<template>
    <div class="using" ref="using">
        <canvas />
    </div>
</template>

<style scoped lang="scss">
.using {
    height: 400px;
    background: linear-gradient(-45deg, #4d9eff, #ef58a9);
    background-size: 200% 200%;
    animation: background 3s linear infinite;

    // 动画
    @keyframes background {
        0%,
        100% {
            background-position: 0 0;
        }
        50% {
            background-position: 100% 100%;
        }
    }

    canvas {
        width: 300px;
        height: 100%;
    }
}
</style>
